package pl.edu.agh.ros.node;

import java.util.List;

import org.jivesoftware.smack.packet.Message;
import org.ros.node.NodeConfiguration;

import pl.edu.agh.ros.node.conf.ProxyNodeConfiguration;
import pl.edu.agh.ros.node.conf.XMPPConfiguration;
import pl.edu.agh.ros.node.manager.IServerManager;

public class ProxyBroadcaster<T extends org.ros.message.Message> extends ProxyPublisher<T> {

	private String loggedUser;
	private final ProxyNodeConfiguration proxyTopicConfiguration;

	public ProxyBroadcaster(IServerManager serverManager, XMPPConfiguration xmppConfiguration,
			ProxyNodeConfiguration proxyTopicConfiguration, String nodeName) {
		super(serverManager, xmppConfiguration, proxyTopicConfiguration, nodeName);
		this.proxyTopicConfiguration = proxyTopicConfiguration;
	}

	@Override
	public void main(NodeConfiguration nodeConfiguration) throws Exception {
		super.main(nodeConfiguration);
		loggedUser = xmppConnector.getConnection().getUser().split("/")[0]; //$NON-NLS-1$
	}

	@Override
	protected void onXMPPMessage(Message message) {
		super.onXMPPMessage(message);

		List<String> subscribers = serverManager.getSubscribers(proxyTopicConfiguration.getName());
		subscribers.remove(loggedUser);
		subscribers.remove(message.getFrom());
		for (String subscriber : subscribers) {
			xmppConnector.sendMessage(message, subscriber);
		}
	}

}
